using System;
using System.Windows.Forms;
using CSW.Framework.Common;
using CSW.Framework.UI.Binding;
using DevExpress.XtraEditors.DXErrorProvider;
using ErrorType = CSW.Framework.Common.Binding.ValueTypes.ErrorType;
using DXErrorType = DevExpress.XtraEditors.DXErrorProvider.ErrorType;

namespace CSW.Framework.UI.DevEx.Binding
{
    /// <summary>
    /// Wraps the <see cref="DXErrorProvider" /> error provider.  See <see cref="Binder" />.
    /// </summary>
    public class DXError : IErrorWrapper
    {
        private readonly DXErrorProvider m_DXErrorProvider;

        /// <summary>
        /// Initializes a new instance of the <see cref="DXError"/> class.
        /// </summary>
        /// <param name="dxErrorProvider">The DXErrorProvider.</param>
        public DXError(DXErrorProvider dxErrorProvider)
        {
            Guard.ArgumentNotNull(dxErrorProvider, "dxErrorProvider");

            m_DXErrorProvider = dxErrorProvider;
        }

        /// <summary>
        /// Sets the error of a control.
        /// </summary>
        /// <param name="control">The control.</param>
        /// <param name="text">The error text.</param>
        /// <param name="errorType">The type of error.</param>
        public void SetError(Control control, string text, ErrorType errorType)
        {
            Guard.ArgumentNotNull(control, "control");

            DXErrorType dxErrorType = GetDXErrorType(errorType);

            m_DXErrorProvider.SetError(control, text, dxErrorType);
        }

        /// <summary>
        /// Clears the error of a control.
        /// </summary>
        /// <param name="control">The control.</param>
        public void ClearError(Control control)
        {
            Guard.ArgumentNotNull(control, "control");

            SetError(control, null, ErrorType.None);
        }

        /// <summary>
        /// Gets the DevExpress error type.
        /// </summary>
        /// <param name="errorType">Type of the error.</param>
        /// <returns>The DevExpress error type.</returns>
        public static DXErrorType GetDXErrorType(ErrorType errorType)
        {
            DXErrorType dxErrorType;

            switch (errorType)
            {
                case ErrorType.None:
                    dxErrorType = DXErrorType.None;
                    break;

                case ErrorType.Warning:
                    dxErrorType = DXErrorType.Warning;
                    break;

                case ErrorType.Information:
                    dxErrorType = DXErrorType.Information;
                    break;

                case ErrorType.Error:
                    dxErrorType = DXErrorType.Critical;
                    break;

                default:
                    throw new Exception(string.Format("Unhandled ErrorType '{0}'", errorType));
            }

            return dxErrorType;
        }
    }
}